<?php

declare (strict_types = 1);

namespace App\Middleware\Auth;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Wuxian\WebUtils\JwtUtils;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JwtTokenMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 根据具体业务判断逻辑走向，这里假设用户携带的token有效
        $authorization = $this->request->getHeader('authorization')[0] ?? '';
        try {
            $checkJwtToken = JwtUtils::checkToken($authorization, config('web.admin_jwt_key'));
            // 检查这个用户状态,以及最新的绑定公司情况
            \Hyperf\Utils\Context::set('jwt_token', $checkJwtToken);
            return $handler->handle($request);
        }catch (\Exception $exception) {
            throw new BusinessException(ErrorCode::ERR_BUESSUS, $exception->getMessage());
        }
    }
}
